package com.glsc.ngateway.platform.service;

import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Map;
import java.util.Random;

/**
 * @author mengl
 * @date 2021/08/19
 */
@Service
public class ValidateCodeService {

    private int width = 140;// 图片宽
    private int height = 40;// 图片高
    private int lineSize = 5;// 干扰线数量

    private Random random = new Random();

    /**
     * 生成随机图片
     */
    public BufferedImage getImage(String rangeString) {
        // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        // 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        Graphics2D imageGraphics = image.createGraphics();
        imageGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0));//设置透明图
        imageGraphics.dispose();
        imageGraphics = image.createGraphics();

        // 绘制随机字符
        imageGraphics.translate(random.nextInt(5), random.nextInt(5));
        int xBase = 20;
//        int size = random.nextInt(10) + 20;
        Font font = new Font("Arial", Font.BOLD, 28);
        imageGraphics.setFont(font);//字体大小
        for (int i = 0; i < rangeString.length(); i++) {
            random.nextInt();
            char chart = rangeString.charAt(i);
            String draw = String.valueOf(chart);
            imageGraphics.setColor(new Color(random.nextInt(255), random.nextInt(55) + 200, random.nextInt(255)));
            imageGraphics.drawString(draw, xBase, 30);
            xBase = xBase + 17;
        }
        // 绘制干扰线
        for (int i = 0; i <= lineSize; i++) {
            drawLine(imageGraphics);
        }
        imageGraphics.dispose();
        return image;
    }

    /**
     * 绘制干扰线
     */
    private void drawLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(width - x);
        int yl = random.nextInt(height - y);
        g.setColor(new Color(random.nextInt(255), random.nextInt(55) + 200, random.nextInt(255)));
        g.drawLine(x, y, x + xl, y + yl);
    }

    public Map<String, String> getRandom() {
        int t1 = random.nextInt(10);
        int t2 = random.nextInt(10);

        int t = random.nextInt(3);
        String t3;
        int value;
        if (t == 0) {
            t3 = "+";
            value = t1 + t2;
        } else if (t == 1) {
            t3 = "-";
            value = t1 - t2;
        } else {
            t3 = "*";
            value = t1 * t2;
        }
        String randomStr = "" + t1 + t3 + t2 + "=";
        Map<String, String> res = Maps.newHashMap();
        res.put("randomStr", randomStr);
        res.put("redisStr", value + "");
        return res;
    }
}
